package com.springboot02amqp.amqp.controller;

import com.springboot02amqp.amqp.bean.Book;
import com.springboot02amqp.amqp.service.BookService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/test")
public class AmqpController  {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    BookService bookService;

    @GetMapping("/send")
    public String sendMsg() {
        for (int i = 0; i < 10; i++) {   // 发送10次消息
            rabbitTemplate.convertAndSend("test_exchange", "test_queue", new Book("Java程序设计", "Java教研室"));
            System.out.println("生产者发送第"+(i+1)+"条消息======>");
        }

        return "发送成功";
    }

    @GetMapping("/receive")
    public void receive() {
        Message message;
        while ((message = rabbitTemplate.receive("test_queue")) != null) {
            System.out.println("消费者接收消息======>" + new String(message.getBody()));
        }
        System.out.println("没有消息");
    }
}
